package com.anrongtec.zcpt.tab01;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.webkit.WebView;
import android.widget.TextView;

import com.anrong.sdk.util.log.LogUtil;
import com.anrongtec.zcpt.R;
import com.anrongtec.zcpt.base.BaseFragment;
import com.anrongtec.zcpt.module.AppModel;
import com.anrongtec.zcpt.util.Util;
import com.art.base.util.ApkUtils;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter.OnItemClickListener;
import com.zhy.adapter.recyclerview.base.ViewHolder;
import com.zhy.adapter.recyclerview.wrapper.EmptyWrapper;
import com.zhy.adapter.recyclerview.wrapper.LoadMoreWrapper;

import java.util.ArrayList;
import java.util.List;

/**
 * 我的应用 =====为了解决首页显示的只是从商店下载额
 *
 * @author cxy
 */
public class TabFirstFragmentOld extends BaseFragment implements OnClickListener {

    private RecyclerView rv;

    private WebView webView;

    private TextView tv_button;
    private SwipeRefreshLayout swipe_refresh;
    private CommonAdapter<AppModel> adapter;
    // private List<FunctionModel> functions;
    private List<AppModel> apps, newApps;
    private AppModel tempApp;
    private TextView tv_header;
    private EmptyWrapper empty;
    private LoadMoreWrapper loadMoreWrapper;
    private static final int SPAN_COUNT = 4;

    private boolean isGetAppsInfo = true;// 是否正在获取app信息

    private TextView tv_num;

    private Animation in, out;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    empty.setEmptyView(R.layout.empty_view);
                    rv.setAdapter(empty);
                    apps.clear();
                    apps.addAll(newApps);
                    empty.notifyDataSetChanged();
                    if (swipe_refresh != null && swipe_refresh.isRefreshing()) {
                        swipe_refresh.setRefreshing(false);
                    }
                    break;

                default:
                    break;
            }

            tv_num.setText("我的应用共" + apps.size() + "款");

        }
    };

    /**
     * 展示数据的url
     */
    // private String url;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        initData();
        View v = inflater.inflate(R.layout.fragment_tab_first, null);
        initViews(v);

        return v;
    }

    public void refresh() {
        // newApps = Util.getAppsInfo(getActivity());
        newApps = Util.getAppsFromMaket(getActivity());
        handler.sendEmptyMessage(1);
    }

    /**
     * 初始化数据
     */
    @Override
    protected void initData() {
        apps = new ArrayList<AppModel>();
        newApps = new ArrayList<AppModel>();

        // url = DDApp.dApp.getCurrentUser().getUrl();

        getAppsInfo();
    }

    /**
     * 初始化控件
     */
    @Override
    protected void initViews(View view) {
        tv_num = (TextView) view.findViewById(R.id.tv_tab01_num);

        tv_button = (TextView) view.findViewById(R.id.tv_tab01_button);
        tv_button.setVisibility(View.GONE);
        tv_button.setOnClickListener(this);

        initRecyclerView(view);
        // if (TextUtils.isEmpty(url)) {
        // tv_button.setVisibility(View.GONE);
        // }else {
        // initWebView(view);
        // }

        initSwipeRefresh(view);
    }

    /**
     * 初始化下拉刷新
     *
     * @param view
     */
    private void initSwipeRefresh(View view) {
        swipe_refresh = (SwipeRefreshLayout) view.findViewById(R.id.swipe_tab01_refresh);
        swipe_refresh.setEnabled(false);
        swipe_refresh.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_orange_light,
                android.R.color.holo_green_light);
        swipe_refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                swipe_refresh.setRefreshing(true);
                getAppsInfo();
            }
        });
    }

    /**
     * 初始化webview
     *
     * @param view
     */
    // private void initWebView(View view) {
    // webView = (WebView) view.findViewById(R.id.wv_tab01);
    // webView.getSettings().setJavaScriptEnabled(true);
    // webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
    // webView.getSettings().setSupportMultipleWindows(true);
    // webView.setWebChromeClient(new WebChromeClient());
    // webView.setWebViewClient(new WebViewClient(){
    //
    // });
    //
    //// wv_data.loadUrl("file:///android_asset/info.html");
    // webView.loadUrl(url);
    // LogUtil.trace(Log.DEBUG, "webview", url);
    //// webView.loadUrl("http://www.google.cn");
    // in = AnimationUtils.loadAnimation(getContext(), android.R.anim.fade_in);
    // out = AnimationUtils.loadAnimation(getContext(),
    // android.R.anim.fade_out);
    // }

    /**
     * 初始化recyclerview
     *
     * @param view
     */
    private void initRecyclerView(View view) {
        rv = (RecyclerView) view.findViewById(R.id.tab01_recyclerview);
        rv.setLayoutManager(new GridLayoutManager(getContext(), SPAN_COUNT, GridLayoutManager.VERTICAL, false));

        adapter = new CommonAdapter<AppModel>(getContext(), R.layout.item_tab_first, apps) {

            @Override
            protected void convert(ViewHolder holder, AppModel t, int position) {
                holder.setImageDrawable(R.id.iv_tab01_item, t.getLocalIcon());
                holder.setText(R.id.tv_tab01_item, t.getAppName());
            }

        };

        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                if (apps.get(position).getActivity() == null||apps.get(position).getActivity().equals("")) {
                    ApkUtils.openAPP(getContext(), apps.get(position).getAppPackName());
                } else {
                    LogUtil.trace(Log.ERROR, "22222", apps.get(position).getActivity());
                    ApkUtils.openAPP(getContext(), apps.get(position).getAppPackName(),
                            apps.get(position).getActivity());
                   // ApkUtils.openDefaultApp(getActivity(),apps.get(position).getAppPackName());
                }
               // ApkUtils.openDefaultApp(getActivity(),apps.get(position).getAppPackName());
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });

        empty = new EmptyWrapper(adapter);
        empty.setEmptyView(R.layout.loading_view);

        // loadMoreWrapper = new LoadMoreWrapper(empty);
        // loadMoreWrapper.setLoadMoreView(R.layout.default_loading);
        // loadMoreWrapper.setOnLoadMoreListener(new OnLoadMoreListener() {
        // @Override
        // public void onLoadMoreRequested() {
        // if (isGetAppsInfo) {
        // return;
        // }
        // apps.addAll(apps);
        // handler.sendEmptyMessageDelayed(1, 3000);
        // }
        // });

        rv.setAdapter(empty);
    }

    @Override
    protected void initEvents(View view) {

    }

    /**
     * 获取非系统应用
     */
    public void getAppsInfo() {

        Util.post(new Runnable() {
            @Override
            public void run() {
                // newApps = Util.getAppsInfo(getContext());
                newApps = Util.getAppsFromMaket(getActivity());
                // handler.sendEmptyMessageDelayed(1, 1000);
                handler.sendEmptyMessage(1);
            }
        });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_tab01_button:
                if (webView.getVisibility() == View.GONE) {
                    webView.startAnimation(in);
                    webView.setVisibility(View.VISIBLE);
                    tv_button.setText("我的应用");
                } else {
                    webView.startAnimation(out);
                    webView.setVisibility(View.GONE);
                    tv_button.setText("统计分析");
                }
                break;

            default:
                break;
        }
    }

}
